package com.gtenacg.cartoonservice.controller;

import com.gtenacg.cartoonservice.common.annotation.CheckToken;
import com.gtenacg.cartoonservice.common.Const;
import com.gtenacg.cartoonservice.compent.MyRestTemplate;
import com.gtenacg.cartoonservice.common.Result;
import com.gtenacg.cartoonservice.pojo.model.Cartoon;
import com.gtenacg.cartoonservice.pojo.model.Novel;
import com.gtenacg.cartoonservice.service.CartoonService;
import com.gtenacg.cartoonservice.service.NovelService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Collections;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FileController {

    final CartoonService cartoonService;
    final NovelService novelService;

    @CheckToken
    @PostMapping("/upload/cartoonCover/{id}")
    public Result<Void> uploadCartoonCover(@RequestParam("file") MultipartFile file, @PathVariable Integer id) throws IOException {
        log.info("上传漫画封面: {}", id);

        Cartoon cartoon = cartoonService.getByCids(Collections.singletonList(id)).get(0);

        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = Const.COVER_NAME + suffix;

        String filePath = Const.CARTOON_PATH + cartoon.getName() + "/" + fileName;
        Result<?> response = MyRestTemplate.FileServiceUpload(file, filePath);
        // 更新
        if (response.getCode() == HttpStatus.OK.value()) {
            cartoon.setCover(Const.FILE_PATH + filePath);
            cartoonService.update(cartoon);
        }

        return Result.success();
    }

    @CheckToken
    @PostMapping("/upload/novelCover/{id}")
    public Result<Void> uploadNovelCover(@RequestParam("file") MultipartFile file, @PathVariable Integer id) throws IOException {
        log.info("上传电子书封面: {}", id);

        Novel novel = novelService.getByNids(Collections.singletonList(id)).get(0);

        String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = Const.COVER_NAME + suffix;

        String filePath = Const.NOVEL_PATH + novel.getName() + "/" + fileName;

        // 上传
        Result<?> response = MyRestTemplate.FileServiceUpload(file, filePath);
        // 更新
        if (response.getCode() == HttpStatus.OK.value()) {
            novel.setCover(Const.FILE_PATH + filePath);
            novelService.update(novel);
        }


        return Result.success();
    }

}